package cn.mrlong.base.utils

import android.app.Activity
import android.app.NotificationManager
import android.content.Context
import kotlin.collections.ArrayList

/**
 * activity管理类
 * 作者：BINGO
 * 时间：2021/03/25 16:26
 */
class ActivityManager private constructor() {
    /**
     * 构造方法初始化容器
     */
    init {
        activityStack = ArrayList<Activity>()
    }

    companion object {
        //存储activity的栈
        private lateinit var activityStack: ArrayList<Activity>

        //单例
        private var instance: ActivityManager? = null
            get() {
                if (null == field) {
                    field = ActivityManager()
                }
                return field
            }

        //这里不能直接使用getInstance() 与Kt自动生成的重名了
        fun get(): ActivityManager {
            return instance!!
        }
    }

    /**
     * 是否包含指定的ativity/或者指定activity是否在运行
     * @param activity Activity
     * @return Boolean
     */
    public fun contains(activity: Activity): Boolean {
        return activityStack.contains(activity)
    }

    /**
     * 退出应用程序
     * @param context
     */
    public fun exitApp(context: Context) {
        try {
            finishAllActivity()
            val notificationManager: NotificationManager =
                context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.cancelAll()
            android.os.Process.killProcess(android.os.Process.myPid())
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 结束所有 activity :
     */
    public fun finishAllActivity() {
        if (activityStack.size > 0) {
            for (activity in activityStack) {
                activity.finish()
            }
            activityStack.clear()
        }
    }


    /**
     * 移除activity
     */
    public fun remove(activity: Activity) {
        if (activityStack.size > 0) {
            activityStack.remove(activity)
        }
    }

    /**
     * 压栈：添加activity
     */
    public fun push(activity: Activity) {
        activityStack.add(activity)
    }
}